package ntd.util.frame.action.ai;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.modular.extra.ai.FactoryAiOpt;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.action.bean.VisionModelDo;
import ntd.util.frame.javacv.tool.ToolAiUserSites;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActionAiStatistics extends ActionAbs {

    public static final Map<String, String> whereDateMap = new HashMap<>();

    static {
        whereDateMap.put("day", "to_days(analytics_time) = to_days(now())");
        whereDateMap.put("month", "DATE_FORMAT(analytics_time, '%Y%m') = DATE_FORMAT( CURDATE( ) , '%Y%m')");
        whereDateMap.put("year", "YEAR(analytics_time)=YEAR(NOW())");
    }

    @Override
    public ActionInfo info() {
        return new ActionInfo("AI统计", "ai-statistics", new ActionAiStatistics());
    }

    @Override
    public ActionOutBo handle() {
        // 执行逻辑,day、month、year
        String type = actionInBo.getParamStr("type");
        String mn = actionInBo.getParamStr("mn");
        if (StrUtil.isEmpty(type)) {
            throw new ComException("参数有误");
        }

        //数据库
        Db use = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));

        String sql = "SELECT COUNT(*) AS num,ai_mode_type FROM airesult WHERE isAlert = 1 and {}";

        String dateSql = whereDateMap.get(type);

        if (StrUtil.isBlank(dateSql)) {
            throw new ComException("未知的时间类型！");
        }

        if (!StrUtil.isEmpty(mn)) {
            if (!ToolAiUserSites.IsExistMn(mn)){
                throw new ComException("没有该站点的权限，请联系管理员！");
            }

            sql += StrUtil.format(" and siteMn = '{}'", mn);
        }

        sql += " GROUP BY ai_mode_type";

        sql = StrUtil.format(sql, dateSql);


        List<Entity> result = null;
        try {
            result = use.query(sql);
        } catch (SQLException e) {
            StaticLog.error(e, "[AI][统计][{}]失败...");
        }

        Map<String, Entity> map = CollStreamUtil.toIdentityMap(result, entity -> entity.getStr("ai_mode_type"));

        Map<String, Integer> countMap = new HashMap<>();

        for (VisionModelDo visionModelDo : FactoryAiOpt.OPT_VISION_MODEL.cacheListAll()) {
            countMap.put(StrUtil.lowerFirst(visionModelDo.getCode()) + "Count", getNum(map, visionModelDo));
        }

        return new ActionOutBo(countMap);
    }

    private static Integer getNum(Map<String, Entity> map, VisionModelDo visionModelDo) {
        return ObjectUtil.defaultIfNull(
                map.get(visionModelDo.getCode()), defaultEntity()).getInt("num");
    }

    private static Entity defaultEntity() {
        return new Entity().set("num", 0);
    }
}
